/**
 * websocket相关
 *
 * @author tanghom<tanghom@qq.com> 2016/4/28
 */
var hostPath = window.location.host;
var websocket;
if (window.WebSocket) {
    websocket = new WebSocket("ws://" + hostPath + "/webSocketServer");
} else if (window.MozWebSocket) {
    websocket = new MozWebSocket("ws://" + hostPath + "/webSocketServer");
} else {
    websocket = new SockJS("http://" + hostPath + "/sockjs/webSocketServer");
}
websocket.onopen = function (evnt) {
    console.log('websocket.onopen');
};
websocket.onmessage = function (evnt) {
    notify(evnt.data);//消息通知
    weidu();
    console.log('websocket.onmessage');
};
websocket.onerror = function (evnt) {
    console.log('websocket.onerror');
};
websocket.onclose = function (evnt) {
    console.log('websocket.onclose');
};
/*查询未读消息数*/
function unread() {
    window.setInterval(weidu(), 30000);
}
function weidu() {
    $.ajax({
        type: "GET",
        url: webPath+"/msg/unread.shtml",
        success: function (result) {
            if (result > 0) {
                $(".message-icon").addClass("active");
                $(".message-icon i").show().text(result);
                $(".message-icon i").css({"-webkit-animation": "twinkling 1s infinite ease-in-out"}); //在对象element中添加
            } else {
                $(".message-icon").removeClass("active");
            }
        }
    });
}
//html5通知
function notify(data) {
    var data = eval("(" + data + ")");
    var title = data.title;
    var msg = data.msg;
    if (window.Notification) {
        console.log(window.Notification.permission);
        if (window.Notification.permission == 'granted') {
            var instance = new window.Notification(title, {'icon': 'img/favicon.png', 'body': msg});
            instance.onclick = function () {
            };
            instance.onerror = function () {
            };
            instance.onshow = function () {
            };
            instance.onclose = function () {
            };
            return false;
        } else {
            window.Notification.requestPermission(function () {
                console.log('Permissions state: ' + window.Notification.permission);
            });
        }
    }
}